package 单例模式;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lenovo
 * Date: 2022-10-04
 * Time: 20:25
 */
class MyBlockingQ{
    //数组
    int[] arr = new int[10];
    int head = 0;//头
    int tail = 0;//尾
    int size = 0;//计数器
    //添加元素
    public void put(int n) throws InterruptedException {
        synchronized (this){
            while(size >= arr.length){
             wait();//阻塞 等到take里删除元素调用notify唤醒这里的wait
            }
            arr[tail] = n;
            tail++;
            if(tail>= arr.length){//从头开始
                tail =0;
            }
            size++;
            notify();//唤醒take里的wait

        }

    }
    //删除元素
    public Integer take() throws InterruptedException {
        synchronized (this){
            while (size == 0){
                wait();//阻塞 等到put里增加元素调用notify唤醒这里的wait
            }
            int ret = arr[head];
            head++;
            if(head>=arr.length){//从头开始
                head = 0;
            }
            size--;
            notify();//唤醒put里的wait
            return  ret;
        }

    }
}
public class demo6 {
    public static void main(String[] args) {
        MyBlockingQ q = new MyBlockingQ();
      Thread t1 = new Thread(()->{
          int n = 1;
         while (true){
             try {
                 q.put(n);
                 System.out.println("生产者生产元素:"+n);
                 n++;
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
         }
      });

      Thread t2 = new Thread(()->{
         while (true){
             try {
                 int ret = q.take();
                 System.out.println("消费者消费元素:"+ret);
                 Thread.sleep(500);
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
         }
      });
        t1.start();
      t2.start();
    }
}
